package com.magus.project.yddemo.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.annotation.JsonView;
import com.magus.framework.core.controller.BaseController;
import com.magus.framework.core.entity.BaseTreeNode;
import com.magus.framework.core.entity.BaseTreeNode.TreeWithCheckedView;
import com.magus.framework.core.entity.BaseTreeNode.TreeWithOutCheckedView;
import com.magus.framework.core.exception.app.ControllerException;
import com.magus.framework.core.persistence.SearchFilter;
import com.magus.framework.core.util.lang.StringUtils;
import com.magus.framework.core.webbean.TreeResult;
import com.magus.framework.system.annotation.AppGroupInfo;
import com.magus.framework.system.entity.Company;
import com.magus.framework.system.service.CompanyService;
import com.magus.project.yddemo.entity.BenchmarkValue;
import com.magus.project.yddemo.entity.Indicator;
import com.magus.project.yddemo.entity.IndicatorData;
import com.magus.project.yddemo.entity.IndicatorDetail;
import com.magus.project.yddemo.entity.IndicatorPackage;
import com.magus.project.yddemo.service.BenchmarkValueService;
import com.magus.project.yddemo.service.IndicatorDataService;
import com.magus.project.yddemo.service.IndicatorDetailService;
import com.magus.project.yddemo.service.IndicatorPackageService;
import com.magus.project.yddemo.vobean.BenchamarkSurroundVoBean;
import com.magus.project.yddemo.vobean.BenchmarkDesignValueVoBean;
import com.magus.project.yddemo.vobean.BenchmarkUnitVoBean;
import com.magus.project.yddemo.vobean.BenchmarkVoBean;
import com.magus.sis.common.entity.ComUnit;
import com.magus.sis.common.service.ComUnitService;

import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 
 * @author wenyu.han
 * @date 2018-01-22 12:56:25
 */
@ApiIgnore
@RestController
@RequestMapping("/yddemo/benchmarks")
@AppGroupInfo(key = "yddemo:benchmark", name = "对标配置", appKey = "yddemo")
public class BenchmarkController extends BaseController {

	@Autowired
	private CompanyService companyService;

	@Autowired
	private IndicatorPackageService packageService;

	@Autowired
	private IndicatorDetailService detailService;

	@Autowired
	private BenchmarkValueService benchmarkService;

	@Autowired
	private IndicatorDataService dataService;

	@Autowired
	private ComUnitService unitService;

	private SimpleDateFormat year = new SimpleDateFormat("yyyy");
	private SimpleDateFormat yearMonth = new SimpleDateFormat("yyyy-MM");
	private SimpleDateFormat yearMonthDay = new SimpleDateFormat("yyyy-MM-dd");

	/**
	 * 对标配置树组件加载
	 * 
	 * @param node
	 * @return
	 */
	@GetMapping("/{node}")
	@JsonView(TreeWithOutCheckedView.class)
	ResponseEntity<TreeResult> findTree(@PathVariable String node) {
		TreeResult result = new TreeResult();

		String[] nodes = StringUtils.split(node, "_");

		if (nodes.length != 2) {
			throw new ControllerException("请求参数出错：" + node);
		}

		String nodeType = nodes[0];
		String nodeId = nodes[1];

		result.setChildren(findChildrenByNode(nodeType, nodeId));
		return ResponseEntity.ok(result);
	}

	/**
	 * 对标配置数组件加载调用方法
	 * 
	 * @param nodeType
	 * @param nodeId
	 * @return
	 */
	private List<BaseTreeNode> findChildrenByNode(String nodeType, String nodeId) {
		List<BaseTreeNode> nodes = new ArrayList<>();
		String nodePid = nodeType + "_" + nodeId;

		List<SearchFilter> searchFilters = new ArrayList<SearchFilter>();
		searchFilters.add(SearchFilter.equal("deleted", Boolean.FALSE));
		Sort sort = new Sort(Direction.ASC, "order");
		if ("root".equalsIgnoreCase(nodeType)) {
			searchFilters.add(SearchFilter.isNull("parent"));
			Specification<Company> spec = buildFilterRequest(searchFilters);
			List<Company> companyList = companyService.findAll(spec, sort);
			companyList.stream().forEach(company -> {
				company.setText(company.getName());
				company.setLeaf(Boolean.FALSE);
				company.setExpanded(Boolean.FALSE);
				company.setIconCls("menuCommon");
				company.setNodePid(nodePid);
				nodes.add(company);
			});
		}

		if ("company".equalsIgnoreCase(nodeType)) {
			// 公司->子公司
			searchFilters.add(SearchFilter.equal("parent.id", nodeId));
			Specification<Company> spec = buildFilterRequest(searchFilters);
			List<Company> companyList = companyService.findAll(spec, sort);
			companyList.stream().forEach(company -> {
				company.setText(company.getName());
				company.setLeaf(Boolean.FALSE);
				company.setIconCls("menuCommon");
				company.setNodePid(nodePid);
				nodes.add(company);
			});
			searchFilters = new ArrayList<SearchFilter>();
			searchFilters.add(SearchFilter.equal("company.id", nodeId));
			Specification<IndicatorPackage> packageSpec = buildFilterRequest(searchFilters);
			List<IndicatorPackage> packageList = packageService.findAll(packageSpec);
			packageList.stream().forEach(pack -> {
				BaseTreeNode node = new BaseTreeNode();
				node.setText(pack.getName());
				node.setEntityId(pack.getId());
				node.setEntityType(pack.getClass().getSimpleName());
				node.setId(pack.getId());
				node.setNodeId(pack.getClass().getSimpleName() + "_" + pack.getId());
				// node.setIconCls("menuManual");
				node.setLeaf(Boolean.TRUE);
				node.setNodePid(nodePid);
				nodes.add(node);
			});
		}
		return nodes;
	}

	@GetMapping(params = { "nodeId" })
	@ApiOperation(value = "查询指标包指标", notes = "返回指标包的所有指标信息")
	ResponseEntity<List<BenchmarkVoBean>> findAllByIndicator(@RequestParam String nodeId) {
		// 获取指标包Id
		String[] nodes = StringUtils.split(nodeId, "_");
		nodeId = nodes[1];
		// 根据指标包Id查询相关数据并封装到vobean中
		List<SearchFilter> searchFilters = new ArrayList<>();
		searchFilters.add(SearchFilter.equal("indicatorPackage.id", nodeId));
		Specification<IndicatorDetail> detailSpec = buildFilterRequest(searchFilters);
		List<IndicatorDetail> detailList = detailService.findAll(detailSpec);
		List<BenchmarkVoBean> voBeanList = new ArrayList<>();
		for (IndicatorDetail id : detailList) {
			BenchmarkVoBean voBean = new BenchmarkVoBean();
			voBean.setIndicatorId(id.getIndicator().getId());
			voBean.setIndicatorName(id.getIndicator().getName());
			voBean.setUnit(id.getIndicator().getUnit());
			voBean.setDetailId(id.getId());
			searchFilters = new ArrayList<>();
			searchFilters.add(SearchFilter.equal("indicatorDetail.id", id.getId()));
			Specification<BenchmarkValue> benchmarkSpec = buildFilterRequest(searchFilters);
			BenchmarkValue benchmark = benchmarkService.findOne(benchmarkSpec);
			if (benchmark != null) {
				voBean.setDesignValue(benchmark.getDesignValue().toString());
			} else {
				voBean.setDesignValue("");
			}

			voBeanList.add(voBean);
		}
		return ResponseEntity.ok(voBeanList);
	}

	@PutMapping
	@RequiresPermissions("yddemo:benchmark:manage")
	@ApiOperation(value = "保存指标设计值数据", notes = "返回保存后的指标数据")
	ResponseEntity<BenchmarkVoBean> updateIndicatorDesign(@RequestBody List<BenchmarkVoBean> benchmarkVoBeanList,
			BindingResult result) {
		List<BenchmarkValue> benchmarkList = new ArrayList<>();
		for (BenchmarkVoBean bean : benchmarkVoBeanList) {
			List<SearchFilter> searchFilters = new ArrayList<>();
			searchFilters.add(SearchFilter.equal("indicatorDetail.id", bean.getDetailId()));
			Specification<BenchmarkValue> benchmarkSpec = buildFilterRequest(searchFilters);
			BenchmarkValue benchmark = benchmarkService.findOne(benchmarkSpec);
			if (benchmark != null) {
				benchmark.setDesignValue(Double.valueOf(bean.getDesignValue()));
			} else {
				benchmark = new BenchmarkValue();
				searchFilters = new ArrayList<>();
				searchFilters.add(SearchFilter.equal("id", bean.getDetailId()));
				Specification<IndicatorDetail> detailSpec = buildFilterRequest(searchFilters);
				IndicatorDetail detail = detailService.findOne(detailSpec);
				benchmark.setDesignValue(Double.valueOf(bean.getDesignValue()));
				benchmark.setIndicatorDetail(detail);
			}
			benchmarkList.add(benchmark);
		}
		benchmarkService.save(benchmarkList);
		return ResponseEntity.noContent().build();
	}

	@GetMapping("/findIndicators")
	@ApiOperation(value = "查询指标弹出框数据", notes = "返回指标符合条件的所有指标数据")
	ResponseEntity<List<IndicatorDetail>> findByIndicators(@RequestParam(required = true) String indicators) {
		List<String> indicatorIdList = Arrays.asList(indicators.split(","));
		List<SearchFilter> searchFilters = new ArrayList<>();
		searchFilters.add(SearchFilter.in("id", indicatorIdList));
		Specification<IndicatorDetail> spec = buildFilterRequest(searchFilters);
		List<IndicatorDetail> detailList = detailService.findAll(spec);
		return ResponseEntity.ok(detailList);
	}

	@PostMapping(params = { "content" })
	@ApiOperation(value = "显示指标的详细数据信息", notes = "根据ID展示指标的详细数据")
	ResponseEntity<List<BenchmarkDesignValueVoBean>> findIndicatorByContent(@RequestParam String content,@RequestParam String packageIds,
			@RequestBody List<String> ids) {
		// List<String> ids = new ArrayList<>();
//		List<String> packageIdList = Arrays.asList(packageIds.split(","));
		List<SearchFilter> searchFilters = new ArrayList<>();
		searchFilters.add(SearchFilter.in("id", ids));
//		searchFilters.add(SearchFilter.in("indicatorPackage.id", packageIdList));
		Specification<IndicatorDetail> detailSpec = buildFilterRequest(searchFilters);
		List<IndicatorDetail> detailList = detailService.findAll(detailSpec);
		
		for (IndicatorDetail detail : detailList) {
			ids.add(detail.getId());
		}
		// 1.查询所有对比点的设计值
		searchFilters = new ArrayList<>();
		searchFilters.add(SearchFilter.in("indicatorDetail.id", ids));
		Specification<BenchmarkValue> benchmarkSpec = buildFilterRequest(searchFilters);
		List<BenchmarkValue> benchmarkList = benchmarkService.findAll(benchmarkSpec);

		// 2.查询所有对比点的实际值
		searchFilters = new ArrayList<>();
		searchFilters.add(SearchFilter.in("indicatorDetail.id", ids));
		Specification<IndicatorData> dataSpec = buildFilterRequest(searchFilters);
		List<IndicatorData> dataList = dataService.findAll(dataSpec);

		// 3.将对应的指标数据进行封装
		List<BenchmarkDesignValueVoBean> voBeanList = new ArrayList<>();
		for (IndicatorDetail detail : detailList) {
			BenchmarkDesignValueVoBean voBean = new BenchmarkDesignValueVoBean();
			voBean.setIndicatorName(detail.getIndicator().getName());
			voBean.setCode(detail.getIndicator().getCode());
			List<BenchmarkValue> benchmarkValueList = benchmarkList.stream()
					.filter(t -> detail.getIndicator().getId().equals(t.getIndicatorDetail().getIndicator().getId()))
					.collect(Collectors.toList());
			if (benchmarkValueList.size() > 0) {
				voBean.setDesignValue(benchmarkValueList.get(0).getDesignValue().toString());
			} else {
				voBean.setDesignValue("");
			}
			List<IndicatorData> indicatorDataList = dataList.stream()
					.filter(t -> detail.getIndicator().getId().equals(t.getIndicatorDetail().getIndicator().getId()))
					.collect(Collectors.toList());
			if (indicatorDataList.size() > 0) {
				voBean.setData(indicatorDataList.get(0).getValue().toString());
			} else {
				voBean.setData("");
			}
			// 计算偏差值
			double deviation = 0.00;
			if (benchmarkValueList.size() > 0 && indicatorDataList.size() > 0) {
				deviation = benchmarkValueList.get(0).getDesignValue() - indicatorDataList.get(0).getValue();
				voBean.setDeviation(String.valueOf(deviation));
			} else {
				voBean.setDeviation("");
			}

			voBeanList.add(voBean);
		}

		return ResponseEntity.ok(voBeanList);
	}

	@PostMapping(params = { "unit" })
	@ApiOperation(value = "显示机组指标的详细数据信息", notes = "根据ID展示机组指标的详细数据")
	ResponseEntity<List<BenchmarkUnitVoBean>> findIndicatorByUnit(@RequestParam String unit, @RequestParam String date,
			@RequestParam String dimension,@RequestParam String packageIds, @RequestBody List<Indicator> indicatorList) throws ParseException {
		Date beginTime = new Date();
		Calendar calendar = Calendar.getInstance();
		if (dimension.equals("year")) {
			beginTime = year.parse(date.substring(0, 4));
			calendar.setTime(beginTime);
			calendar.add(Calendar.YEAR, 1);
		} else if (dimension.equals("month")) {
			beginTime = yearMonth.parse(date.substring(0, 7));
			calendar.setTime(beginTime);
			calendar.add(Calendar.MONTH, 1);
		} else {
			beginTime = yearMonthDay.parse(date);
			calendar.setTime(beginTime);
			calendar.add(Calendar.DAY_OF_MONTH, 1);
		}
		Date endTime = calendar.getTime();
		List<BenchmarkUnitVoBean> voBeanList = benchmarkService.findIndicators(indicatorList, beginTime, endTime,packageIds,dimension);
		return ResponseEntity.ok(voBeanList);
	}

	@PostMapping(params = { "surround" })
	@ApiOperation(value = "显示环比指标的详细数据信息", notes = "根据ID展示环比指标的详细数据")
	ResponseEntity<List<BenchamarkSurroundVoBean>> findIndicatorBySurround(@RequestParam String surround,
			@RequestParam String date, @RequestParam String dimension,@RequestParam String packageIds, @RequestBody List<Indicator> indicatorList)
			throws ParseException {
		Date beginTime = new Date();
		Calendar calendar = Calendar.getInstance();
		if (dimension.equals("year")) {
			beginTime = year.parse(date.substring(0, 4));
			calendar.setTime(beginTime);
			calendar.add(Calendar.YEAR, 1);
		} else if (dimension.equals("month")) {
			beginTime = yearMonth.parse(date.substring(0, 7));
			calendar.setTime(beginTime);
			calendar.add(Calendar.MONTH, 1);
		} else {
			beginTime = yearMonthDay.parse(date);
			calendar.setTime(beginTime);
			calendar.add(Calendar.DAY_OF_MONTH, 1);
		}
		Date endTime = calendar.getTime();
		List<BenchamarkSurroundVoBean> voBeanList = benchmarkService.findIndicatorBySurround(indicatorList, beginTime,
				endTime,packageIds);
		return ResponseEntity.ok(voBeanList);
	}

	/**
	 * 设计值对标树组件加载
	 * 
	 * @param node
	 * @param indicatorIds
	 * @return
	 */
	@GetMapping("/dialog/{node}")
	@JsonView(TreeWithCheckedView.class)
	ResponseEntity<TreeResult> findTreeByDialog(@PathVariable String node,
			@RequestParam(required = true) String indicatorIds) {
		List<String> ids = Arrays.asList(indicatorIds.split(","));
		TreeResult result = new TreeResult();

		String[] nodes = StringUtils.split(node, "_");

		if (nodes.length != 2) {
			throw new ControllerException("请求参数出错：" + node);
		}

		String nodeType = nodes[0];
		String nodeId = nodes[1];
		List<BaseTreeNode> nodeList = findTreeByNode(nodeType, nodeId, ids);
		result.setChildren(nodeList);
		return ResponseEntity.ok(result);
	}

	/**
	 * 设计值对标树组件加载调用方法
	 * 
	 * @param nodeType
	 * @param nodeId
	 * @param ids
	 * @return
	 */
	private List<BaseTreeNode> findTreeByNode(String nodeType, String nodeId, List<String> ids) {
		List<BaseTreeNode> nodes = new ArrayList<>();
		String nodePid = nodeType + "_" + nodeId;

		List<SearchFilter> searchFilters = new ArrayList<SearchFilter>();
		searchFilters.add(SearchFilter.equal("deleted", Boolean.FALSE));
		Sort sort = new Sort(Direction.ASC, "order");
		if ("root".equalsIgnoreCase(nodeType)) {
			searchFilters.add(SearchFilter.isNull("parent"));
			Specification<Company> spec = buildFilterRequest(searchFilters);
			List<Company> companyList = companyService.findAll(spec, sort);
			companyList.stream().forEach(company -> {
				company.setText(company.getName());
				company.setLeaf(Boolean.FALSE);
				company.setIconCls("menuCommon");
				company.setNodePid(nodePid);
				nodes.add(company);
			});
		}

		if ("company".equalsIgnoreCase(nodeType)) {
			// 公司->子公司
			searchFilters.add(SearchFilter.equal("parent.id", nodeId));
			Specification<Company> spec = buildFilterRequest(searchFilters);
			List<Company> companyList = companyService.findAll(spec, sort);
			companyList.stream().forEach(company -> {
				company.setText(company.getName());
				company.setLeaf(Boolean.FALSE);
				company.setIconCls("menuCommon");
				company.setNodePid(nodePid);
				nodes.add(company);
			});
			searchFilters = new ArrayList<SearchFilter>();
			searchFilters.add(SearchFilter.equal("company.id", nodeId));
			Specification<IndicatorPackage> packageSpec = buildFilterRequest(searchFilters);
			List<IndicatorPackage> packageList = packageService.findAll(packageSpec);
			packageList.stream().forEach(pack -> {
				BaseTreeNode node = new BaseTreeNode();
				node.setText(pack.getName());
				node.setEntityId(pack.getId());
				node.setEntityType(pack.getClass().getSimpleName());
				node.setId(pack.getId());
				node.setNodeId(pack.getClass().getSimpleName() + "_" + pack.getId());
				node.setIconCls("menuManual");
				node.setLeaf(Boolean.FALSE);
				node.setChecked(Boolean.FALSE);
				for (String id : ids) {
					if (id.equals(pack.getId())) {
						node.setChecked(Boolean.TRUE);
					}
				}
				node.setNodePid(nodePid);
				node.setExpanded(Boolean.TRUE);
				List<SearchFilter> searchs = new ArrayList<SearchFilter>();
				searchs.add(SearchFilter.equal("indicatorPackage.id", pack.getId()));
				Specification<IndicatorDetail> detailSpec = buildFilterRequest(searchs);
				List<IndicatorDetail> detailList = detailService.findAll(detailSpec);
				List<BaseTreeNode> detailNodes = new ArrayList<>();
				detailList.forEach(detail -> {
					BaseTreeNode detailNode = new BaseTreeNode();
					detailNode.setText(detail.getIndicator().getName());
					detailNode.setChecked(Boolean.FALSE);
					for (String id : ids) {
						if (id.equals(detail.getId())) {
							detailNode.setChecked(Boolean.TRUE);
						}
					}
					detailNode.setEntityId(detail.getIndicator().getId());
					detailNode.setEntityType(detail.getClass().getSimpleName());
					detailNode.setId(detail.getId());
					detailNode.setNodeId(detail.getClass().getSimpleName() + "_" + detail.getIndicator().getId());
					detailNode.setLeaf(Boolean.TRUE);
					detailNode.setNodePid(pack.getClass().getSimpleName() + "_" + pack.getId());
					detailNode.setChildren(null);
					detailNodes.add(detailNode);
				});
				node.setChildren(detailNodes);
				nodes.add(node);
			});
		}
		return nodes;
	}

	/**
	 * 机组对标和环比对标，机组树组件加载调用
	 * 
	 * @param node
	 * @param unitIds
	 * @return
	 */
	@GetMapping("/Unitdialog/{node}")
	@JsonView(TreeWithCheckedView.class)
	ResponseEntity<TreeResult> findTreeByUnitDialog(@PathVariable String node,
			@RequestParam(required = true) String unitIds) {
		List<String> ids = Arrays.asList(unitIds.split(","));
		TreeResult result = new TreeResult();

		String[] nodes = StringUtils.split(node, "_");

		if (nodes.length != 2) {
			throw new ControllerException("请求参数出错：" + node);
		}

		String nodeType = nodes[0];
		String nodeId = nodes[1];

		result.setChildren(findTreeByUnitNode(nodeType, nodeId, ids));
		return ResponseEntity.ok(result);
	}

	/**
	 * 机组对标和环比对标，机组树组件加载调用方法
	 * 
	 * @param nodeType
	 * @param nodeId
	 * @param ids
	 * @return
	 */
	private List<BaseTreeNode> findTreeByUnitNode(String nodeType, String nodeId, List<String> ids) {
		List<BaseTreeNode> nodes = new ArrayList<>();
		String nodePid = nodeType + "_" + nodeId;

		List<SearchFilter> searchFilters = new ArrayList<SearchFilter>();
		searchFilters.add(SearchFilter.equal("deleted", Boolean.FALSE));
		Sort sort = new Sort(Direction.ASC, "order");
		if ("root".equalsIgnoreCase(nodeType)) {
			searchFilters.add(SearchFilter.isNull("parent"));
			Specification<Company> spec = buildFilterRequest(searchFilters);
			List<Company> companyList = companyService.findAll(spec, sort);
			companyList.stream().forEach(company -> {
				company.setText(company.getName());
				company.setLeaf(Boolean.FALSE);
				company.setIconCls("menuCommon");
				company.setNodePid(nodePid);
				nodes.add(company);
			});
		}

		if ("company".equalsIgnoreCase(nodeType)) {
			// 公司->子公司
			searchFilters.add(SearchFilter.equal("parent.id", nodeId));
			Specification<Company> spec = buildFilterRequest(searchFilters);
			List<Company> companyList = companyService.findAll(spec, sort);
			companyList.stream().forEach(company -> {
				company.setText(company.getName());
				company.setLeaf(Boolean.FALSE);
				company.setExpanded(Boolean.FALSE);
				company.setIconCls("menuCommon");
				company.setNodePid(nodePid);
				nodes.add(company);
			});
			searchFilters = new ArrayList<SearchFilter>();
			searchFilters.add(SearchFilter.equal("companyId", nodeId));
			Specification<ComUnit> unitSpec = buildFilterRequest(searchFilters);
			List<ComUnit> unitList = unitService.findAll(unitSpec);
			unitList.stream().forEach(unit -> {
				BaseTreeNode node = new BaseTreeNode();
				node.setText(unit.getName());
				node.setChecked(false);
				node.setEntityId(unit.getId());
				node.setEntityType(unit.getClass().getSimpleName());
				node.setId(unit.getId());
				node.setNodeId(unit.getClass().getSimpleName() + "_" + unit.getId());
				node.setIconCls("menuManual");
				node.setChecked(Boolean.FALSE);
				for (String id : ids) {
					if (id.equals(unit.getId())) {
						node.setChecked(Boolean.TRUE);
					}
				}
				node.setLeaf(Boolean.TRUE);
				node.setNodePid(nodePid);
				nodes.add(node);
			});
		}

		return nodes;
	}

	/**
	 * 机组对标和环比对标，指标包树组件加载调用
	 * 
	 * @param node
	 * @param unitIds
	 * @param packageIds
	 * @return
	 */
	@GetMapping("/UnitPackage/{node}")
	@JsonView(TreeWithCheckedView.class)
	ResponseEntity<TreeResult> findTreeByUnitIndicator(@PathVariable String node,
			@RequestParam(required = true) String unitIds, @RequestParam(required = true) String packageIds) {
		List<String> ids = Arrays.asList(unitIds.split(","));
		TreeResult result = new TreeResult();

		String[] nodes = StringUtils.split(node, "_");

		if (nodes.length != 2) {
			throw new ControllerException("请求参数出错：" + node);
		}

		String nodeType = nodes[0];
		String nodeId = nodes[1];

		result.setChildren(findTreeByUnitPackageNode(nodeType, nodeId, ids, packageIds));
		return ResponseEntity.ok(result);
	}

	/**
	 * 机组对标和环比对标，指标包树组件加载调用方法
	 * 
	 * @param nodeType
	 * @param nodeId
	 * @param ids
	 * @param packageIds
	 * @return
	 */
	private List<BaseTreeNode> findTreeByUnitPackageNode(String nodeType, String nodeId, List<String> ids,
			String packageIds) {
		List<BaseTreeNode> nodes = new ArrayList<>();
		String nodePid = nodeType + "_" + nodeId;

		List<SearchFilter> searchFilters = new ArrayList<SearchFilter>();
		searchFilters.add(SearchFilter.in("id", ids));
		searchFilters.add(SearchFilter.equal("deleted", Boolean.FALSE));
		Specification<ComUnit> unitSpec = buildFilterRequest(searchFilters);
		List<ComUnit> unitList = unitService.findAll(unitSpec);
		String companyIds = "";
		for (ComUnit unit : unitList) {
			if (companyIds.indexOf(unit.getCompanyId()) < 0) {
				companyIds += unit.getCompanyId() + ",";
			}
		}

		ids = Arrays.asList(companyIds.split(","));
		List<String> packageIdList = Arrays.asList(packageIds.split(","));
		searchFilters = new ArrayList<SearchFilter>();
		searchFilters.add(SearchFilter.in("company.id", ids));
		if ("root".equalsIgnoreCase(nodeType)) {
			Specification<IndicatorPackage> spec = buildFilterRequest(searchFilters);
			List<IndicatorPackage> packageList = packageService.findAll(spec);
			packageList.stream().forEach(pac -> {
				BaseTreeNode node = new BaseTreeNode();
				node.setText(pac.getName());
				node.setEntityId(pac.getId());
				node.setEntityType(pac.getClass().getSimpleName());
				node.setId(pac.getId());
				node.setNodeId(pac.getClass().getSimpleName() + "_" + pac.getId());
				node.setIconCls("menuCommon");
				node.setChecked(Boolean.FALSE);
				for (String id : packageIdList) {
					if (id.equals(pac.getId())) {
						node.setChecked(Boolean.TRUE);
					}
				}
				node.setNodePid(nodePid);
				node.setLeaf(Boolean.TRUE);
				nodes.add(node);
			});
		}

		return nodes;
	}

	/**
	 * 机组对标和环比对标，指标表格组件加载调用
	 * 
	 * @param packageIds
	 * @return
	 */
	@GetMapping("/UnitIndicator")
	@ApiOperation(value = "查询指标弹出框数据", notes = "返回指标符合条件的所有指标数据")
	ResponseEntity<List<IndicatorDetail>> findUnitByIndicators(@RequestParam(required = true) String packageIds) {
		List<SearchFilter> searchFilters = new ArrayList<>();
		searchFilters.add(SearchFilter.in("indicatorPackage.id", Arrays.asList(packageIds.split(","))));
		Specification<IndicatorDetail> spec = buildFilterRequest(searchFilters);
		List<IndicatorDetail> detailList = detailService.findAll(spec);
		return ResponseEntity.ok(detailList);
	}
}
